package com.zhanggm.hetong.hetong.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.zhanggm.hetong.hetong.config.AjaxResult;
import com.zhanggm.hetong.hetong.entity.Hetong;
import com.zhanggm.hetong.hetong.entity.Log;
import com.zhanggm.hetong.hetong.service.IHetongService;
import com.zhanggm.hetong.hetong.service.ILogService;
import com.zhanggm.hetong.hetong.utils.DownLoadUtil;
import com.zhanggm.hetong.hetong.utils.PdfUtils;
import com.zhanggm.hetong.hetong.utils.WebUtils;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 合同表 前端控制器
 * </p>
 * @author zhanggm
 * @since 2021-09-24
 */
@RestController
@RequestMapping("/hetong")
@Slf4j
public class HetongController {

    @Autowired
    private IHetongService iHetongService;

    @Autowired
    private ILogService iLogService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private RedisTemplate redisTemplate;



    @Value("${file.path}")
    private String filePath;

    @Value("${file.domain}")
    private String fileDoamin;

    /**
     * 分页查询接口
     * @param hetong
     * @param pageNum
     * @param pageSize
     * @return PageInfo
     */
    @GetMapping("getPageInfo")
    public PageInfo getPageInfo(Hetong hetong, @RequestParam("pageNum") Integer pageNum,@RequestParam("pageSize") Integer pageSize) {
        //分页
        PageHelper.startPage(pageNum, pageSize);
        //查询条件
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotEmpty(hetong.getMingcheng())) {
            queryWrapper.like("mingcheng", hetong.getMingcheng());
        }
        List list = iHetongService.list(queryWrapper);
        return new PageInfo(list);
    }

    /**
     * 保存或更新合同
     * @param hetong
     * @return Hetong
     */
    @PostMapping("save")
    @Transactional
    public Hetong save(@RequestBody Hetong hetong) {
        //redis处理接口幂等性
//        String uuid = WebUtils.getRequest().getHeader("uuid");
        log.info("uuid:{}",hetong.getUuid());
        if(!redisTemplate.opsForValue().setIfAbsent(hetong.getUuid(),null,24, TimeUnit.HOURS)){
            return null;
        }
        //新增设置创建时间
        if (hetong.getId() == null) {
            hetong.setAddShijian(LocalDateTime.now());
        }
        //保存跟新成功
        iHetongService.saveOrUpdate(hetong);
        //保存日志
        Log hetonglog = new Log();
        hetonglog.setCreateTime(LocalDateTime.now());
        hetonglog.setJsonData(JSON.toJSONString(hetong));
        hetonglog.setOptDesc("保存合同");
        hetonglog.setUserId(hetong.getUserId());
        iLogService.save(hetonglog);

        //异步发送合同审核通知
        Map<String,Object> msgData = new HashMap<>();
        msgData.put("subject", "合同修改审核通知:" + hetong.getMingcheng());
        msgData.put("recipient", "87941125@qq.com");
        msgData.put("content","合同修改审核通知:" + hetong.getMingcheng());
        msgData.put("extId", UUID.randomUUID().toString());
        kafkaTemplate.send("hetongEmailTopic1",JSON.toJSONString(msgData));
        //返回保存的对象
        return iHetongService.getById(hetong.getId());
    }


    @GetMapping("getById")
    public Hetong getById(Hetong hetong) {
        //返回保存的对象
        return iHetongService.getById(hetong.getId());
    }

    /**
     * 审核
     * @param hetong
     * @return
     */
    @GetMapping("check")
    public Hetong check(Hetong hetong) {
        /*查找合同*/
        Hetong ht = iHetongService.getById(hetong.getId());
        /*修改合同状态*/
        ht.setIsCheck(1);
        iHetongService.saveOrUpdate(ht);
        return ht;
    }

    /**
     * 创建合同pdf
     * @param hetong
     * @throws Exception
     */
    @PostMapping("createPdf")
    public void createPdf(@RequestBody Hetong hetong) throws Exception{
        //查询合同
        hetong = iHetongService.getById(hetong.getId());
        //生成pdf
        ArrayList<Hetong> list = new ArrayList<>();
        list.add(hetong);
        //String url=filePath + contract.getId() + ".pdf";
        Document document = new Document();
        PdfWriter pdfWriter = PdfUtils.createDoc(document, filePath + hetong.getId() + ".pdf");
        PdfUtils.addTable(pdfWriter, new String[] {"ID","合同名称","合同编码"}, new String[] {"id","mingcheng","bianma"}, list, 50, 500, "C:\\Windows\\Fonts\\simsunb.ttf", "/opt/ STFANGSO.TTF");
        PdfUtils.addImg(document,hetong.getPicture(),250,380,50,50);
        document.close();
        pdfWriter.close();
        //pdf转图片
        PdfUtils.pdf2png(filePath+hetong.getId()+".pdf",filePath+hetong.getId()+".jpg");
        FileOutputStream fileOutputStream = new FileOutputStream(filePath+hetong.getMingcheng()+".pdf");
        FileInputStream fileInputStream = new FileInputStream(filePath + hetong.getId() + ".pdf");
        PdfUtils.markImage("D:/work/pic/gz.jpg",fileInputStream,fileOutputStream,"");
    }

    /**
     * 预览合同
     * @param hetong
     * @param response
     * @return
     */
    @RequestMapping("previewPdf")
    public AjaxResult previewPdf(@RequestBody Hetong hetong, HttpServletResponse response){
        String pdf=fileDoamin+hetong.getId()+".pdf";
        return  AjaxResult.ok(pdf);
    }

    /**
     * 下载合同
     * @param hetong
     * @return
     * @throws IOException
     */
    @RequestMapping("download")
    public AjaxResult download(Hetong hetong) throws IOException {
        HttpServletResponse response = WebUtils.getResponse();
        String fileName = filePath+hetong.getId()+".pdf";
        DownLoadUtil.download(response,fileName,hetong.getMingcheng()+hetong.getId()+".pdf",0);
        return AjaxResult.ok();
    }






}
